<template>
    <!-- 主要内容区 -->
    <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-6">
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-2xl font-semibold mb-6">通知公告管理</h2>
            <!-- 搜索和筛选区 -->
            <div class="mb-6 flex items-center">
                <el-input
                    v-model="filters.title"
                    placeholder="请输入标题"
                    class="w-64 mr-4 mb-2"
                />
                <el-input
                    v-model="filters.author"
                    placeholder="请输入发布人"
                    class="w-64 mr-4 mb-2"
                />
                <el-select v-model="filters.status" placeholder="状态" class="w-32 mr-4 mb-2">
                    <el-option label="全部" value="" />
                    <el-option label="已发布" value="published" />
                    <el-option label="草稿" value="draft" />
                </el-select>
                <el-button type="primary" @click="handleSearch" class="!rounded-button mb-2">搜索</el-button>
                <el-button @click="handleReset" class="!rounded-button mb-2">重置</el-button>
            </div>

            <!-- 操作按钮区 -->
            <div class="mb-4 flex">
                <el-button type="primary" @click="showAddDialog" class="!rounded-button mr-2">
                    <el-icon class="mr-1"><plus /></el-icon>新增
                </el-button>
                <el-button type="danger" @click="handleBatchDelete" class="!rounded-button mr-2">
                    <el-icon class="mr-1"><delete /></el-icon>删除
                </el-button>
            </div>

            <!-- 通知列表 -->
            <el-table :data="filteredNotifications" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="序号" width="80" />
                <el-table-column prop="title" label="标题" min-width="200" />
                <el-table-column prop="author" label="发布人" width="120" />
                <el-table-column prop="publishTime" label="发布时间" width="180" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 'published' ? 'success' : 'info'">
                            {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleView(scope.row)" class="whitespace-nowrap">查看</el-button>
                        <el-button link type="primary" @click="showEditDialog(scope.row)" class="whitespace-nowrap">编辑</el-button>
                        <el-button link type="danger" @click="showSingleDeleteConfirm(scope.row)" class="whitespace-nowrap">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="mt-4 flex justify-between items-center">
                <span class="text-sm text-gray-500">
                    共 {{ total }} 条记录
                </span>
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>

            <!-- 新增弹窗 -->
            <el-dialog title="新增通知" v-model="addDialogVisible">
                <el-form :model="addForm">
                    <el-form-item label="标题" label-width="100px">
                        <el-input v-model="addForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="发布人" label-width="100px">
                        <el-input v-model="addForm.author"></el-input>
                    </el-form-item>
                    <el-form-item label="发布时间" label-width="100px">
                        <el-date-picker v-model="addForm.publishTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="状态" label-width="100px">
                        <el-select v-model="addForm.status" placeholder="状态">
                            <el-option label="已发布" value="published" />
                            <el-option label="草稿" value="draft" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="createNotification">保存</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 查看弹窗 -->
            <el-dialog title="查看通知" v-model="viewDialogVisible">
                <el-form :model="viewForm">
                    <el-form-item label="标题" label-width="100px">
                        <el-input v-model="viewForm.title" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="发布人" label-width="100px">
                        <el-input v-model="viewForm.author" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="发布时间" label-width="100px">
                        <el-input v-model="viewForm.publishTime" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="状态" label-width="100px">
                        <el-select v-model="viewForm.status" placeholder="状态" disabled>
                            <el-option label="已发布" value="published" />
                            <el-option label="草稿" value="draft" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="viewDialogVisible = false">关闭</el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 编辑弹窗 -->
            <el-dialog title="编辑通知" v-model="editDialogVisible">
                <el-form :model="editForm">
                    <el-form-item label="标题" label-width="100px">
                        <el-input v-model="editForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="发布人" label-width="100px">
                        <el-input v-model="editForm.author"></el-input>
                    </el-form-item>
                    <el-form-item label="发布时间" label-width="100px">
                        <el-date-picker v-model="editForm.publishTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="状态" label-width="100px">
                        <el-select v-model="editForm.status" placeholder="状态">
                            <el-option label="已发布" value="published" />
                            <el-option label="草稿" value="draft" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="updateNotification">保存</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </main>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Bell, FullScreen, Setting, Plus, Delete, Upload, Download } from '@element-plus/icons-vue';
import { addNotice, editNotice } from '@/api/admin/notice';

const searchKeyword = ref('');
const filters = reactive({
  title: '',
  author: '',
  dateRange: [],
  status: '',
});
const notifications = ref([
  { id: 1, title: '关于2024年春节放假安排的通知', author: '贵州大学', publishTime: '2024-01-15 10:30:00', status: 'published' },
  { id: 2, title: '2024年第一季度业绩报告会议通知', author: '贵州人文科技学院', publishTime: '2024-01-16 14:00:00', status: 'published' },
  { id: 3, title: '新版ERP系统上线培训通知', author: '贵州大学', publishTime: '2024-01-17 09:00:00', status: 'draft' },
  { id: 4, title: '年度员工满意度调查开始通知', author: '贵州大学', publishTime: '2024-01-18 11:30:00', status: 'published' },
  { id: 5, title: '公司五周年庆典活动预告', author: '贵州大学', publishTime: '2024-01-19 16:00:00', status: 'draft' },
]);
const total = ref(100);
const currentPage = ref(1);
const pageSize = ref(10);
const selectedRows = ref([]);
const addDialogVisible = ref(false);
const viewDialogVisible = ref(false);
const editDialogVisible = ref(false);

const addForm = reactive({
  title: '',
  author: '',
  publishTime: '',
  status: ''
});

const viewForm = reactive({
  title: '',
  author: '',
  publishTime: '',
  status: ''
});

const editForm = reactive({
  id: '',
  title: '',
  author: '',
  publishTime: '',
  status: ''
});

//搜索按钮
const handleSearch = () => {
  ElMessage.success('搜索功能已触发');
};

//重置按钮
const handleReset = () => {
  Object.assign(filters, {
    title: '',
    author: '',
    dateRange: [],
    status: '',
  });
};

const handleAdd = () => {
  ElMessage.success('新增通知功能已触发');
};

//新增弹窗
const showAddDialog = () => {
  addForm.title = '';
  addForm.author = '';
  addForm.publishTime = '';
  addForm.status = '';
  addDialogVisible.value = true;

};

//保存新增数据
const createNotification = async () => {
  const addData = await addNotice(addForm).then((res) => {
    if (res.data.code ===200){
      ElMessage.success("通知已成功添加")
      getAllNotice()
      addDialogVisible.value = false;
    }else{
      ElMessage.error("保存失败")
      addDialogVisible.value = false;
      throw new Error("新增内容保存失败")
    }
    return res.data
  })
  console.log(addData)
};

//批量删除
const handleSelectionChange = (val) => {
  selectedRows.value = val;
  console.log('选中的行：', val);
};
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要删除的通知');
    return;
  }
  await ElMessageBox.confirm('确定要删除选中的通知吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(() => {
    ElMessage.info("取消删除!");
    return new Promise(() => {});
  });
  const ids = selectedRows.value.map((item) => item.id);
  const res = await batchDelFrom(ids);
  if (res.data.code === 200) {
    ElMessage.success("删除成功");
    getAllNotice()
  } else {
    ElMessage.error("删除失败");
  }
};

//导入按钮
const handleImport = () => {
  ElMessage.info('导入功能已触发');
};

//导出按钮
const handleExport = () => {
  ElMessage.info('导出功能已触发');
};

//查看弹窗
const handleView = (row) => {
  viewForm.author = row.author;
  viewForm.publishTime = row.publishTime;
  viewForm.status = row.status;
  viewForm.title = row.title;
  viewDialogVisible.value = true;
};

//编辑弹窗
const showEditDialog = (row) => {
  editForm.author = row.author;
  editForm.publishTime = row.publishTime;
  editForm.status = row.status;
  editForm.title = row.title;
  editDialogVisible.value = true;
};

//编辑保存数据
const updateNotification = async () => {
  const index = notifications.value.findIndex(item => item.id === editForm.id);
  const editData = await editNotice(editForm).then((res) => {
    if (res.data.code ===200){
      ElMessage.success("编辑成功")
      getAllNotice()
      editDialogVisible.value = false;
    }else{
      ElMessage.error("编辑失败")
      editDialogVisible.value = false;
      throw new Error("编辑内容保存失败")
    }
    return res.data
  })
  console.log(editData)
};

//单行删除
const showSingleDeleteConfirm = async (row) => {
  ElMessageBox.confirm(`确定要删除通知：${row.title} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).catch(() => {
    ElMessage.info("取消删除!")
    return new Promise(() => {})
  }) 
  const res = await delFrom(row.id)
  getAllNotice()
  console.log(res)
};



const handleSizeChange = (val) => {
  pageSize.value = val;
  // 这里应该重新加载数据
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 这里应该重新加载数据
};



const filteredNotifications = computed(() => {
  return notifications.value.filter(notification =>
    notification.title.includes(filters.title) &&
    notification.author.includes(filters.author) &&
    (filters.status === '' || notification.status === filters.status)
  ).slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
});
</script>


<style scoped>
/* 移除 input type="number" 的默认箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type="number"] {
    -moz-appearance: textfield;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background: #555;
}
</style>
